import io from "socket.io-client";
import store from "@/store";
import { MessageBox, Notification } from "element-ui";

const socket = io();

// 处理服务连接状态
socket.on("connect", () => {
  console.log(">>>> 和服务器已建立连接！");
  store.commit("updateConnected", true);
});

socket.on("disconnect", () => {
  store.commit("updateConnected", false);
});

// 进入房间后，监听room_info事件，获取房间信息
socket.on("room_info", ({ nicknames, holder, lines }) => {
  store.commit("updateNicknames", nicknames);
  store.commit("updateHolder", holder);
  store.commit("updateLines", lines);
});

// 进入房间后，监听user_enter事件，获取其他进入房间的用户信息
socket.on("user_enter", (nickname) => {
  store.commit("addToNicknames", nickname);
});

// 处理游戏开始
socket.on("game_started", (holder, count) => {
  console.log(holder, count);

  store.commit("updateHolder", holder);
  store.commit("updateAnswerCount", count);
  Notification.success(
    `${holder} 作为主持人开始了新游戏，大家可以踊跃猜答案！`
  );
});

socket.on("already_started", (holder, count) => {
  store.commit("updateHolder", holder);
  store.commit("updateAnswerCount", count);
  MessageBox.alert("当前已有游戏在进行中，主持人是：" + holder);
});

// 处理终止游戏
socket.on("game_stopped", () => {
  // 1. 清理相关数据
  store.commit("updateHolder", "");
  store.commit("updateLines", []);

  // 2. 弹出提示消息
  Notification.warning("主持人终止了当前游戏");
});

// 监听线的绘制
socket.on("starting_line", (newLine) => {
  store.commit("drawNewLine", newLine);
});

socket.on("updating_line", (lastLine) => {
  store.commit("updateNewLine", lastLine);
});

socket.on("lines_is_clear", () => {
  store.commit("updateLines", []);
});

// 主持人发送提示信息
socket.on("receive_advice", (advice) => {
  if (advice) {
    Notification.success(`主持人发送提示信息：${advice}`);
    return;
  }
});

// 回答问题
socket.on("game_answered", ({ alreadyDone, success, nickname, answer }) => {
  if (alreadyDone) {
    MessageBox.alert("当前游戏答案已经被猜中，您不能继续猜了！");
    return;
  }
  if (!success) {
    Notification.error(`玩家 ${nickname} 猜的答案不对：${answer}`);
    return;
  }

  MessageBox.alert(`玩家 ${nickname} 猜中正确的答案：${answer}`, {
    title: "恭喜",
    type: "success",
    callback: () => {
      store.commit("updateHolder", "");
      store.commit("updateLines", []);
      socket.emit("reset_game", "");
    },
  });
});

// 玩家退出
socket.on("user_leave", (nickname) => {
  store.commit("delFromNicknames", nickname);

  if (nickname === store.state.holder) {
    store.commit("updateHolder", "");
    store.commit("updateLines", []);
    Notification.error("主持人离开了游戏！");
  }
});

export default socket;
